package com.atguigu.service.impl;

import com.atguigu.dao.BookDao;
import com.atguigu.dao.OrderDao;
import com.atguigu.dao.OrderItemDao;
import com.atguigu.dao.UserDao;
import com.atguigu.dao.impl.BookDaoImpl;
import com.atguigu.dao.impl.OrderDaoImpl;
import com.atguigu.dao.impl.OrderItemDaoImpl;
import com.atguigu.dao.impl.UserDaoImp;
import com.atguigu.pojo.*;
import com.atguigu.service.OrderService;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class OrderServiceImpl implements OrderService {

    private OrderDao orderDao = new OrderDaoImpl();
    private OrderItemDao orderItemDao = new OrderItemDaoImpl();
    private BookDao bookDao  = new BookDaoImpl();

    /**
     * 创建订单
     * @param cart
     * @param userId
     * @return
     */
    @Override
    public String createOrder(Cart cart, Integer userId) {
        //创建订单号(唯一性)
        String orderId = System.currentTimeMillis()+""+userId;
        //创建一个订单对象
        Order order = new Order(orderId, new Date(), new BigDecimal(50), 0, userId);
        //保存订单对象
        orderDao.saveOrder(order);

        //遍历购物车中的商品项,转换为订单项保存到数据库
        for(Map.Entry<Integer, CartItem> entry : cart.getItems().entrySet()){
            //获取购物车中的商品项
            CartItem cartItem = entry.getValue();
            //转换为订单项
            OrderItem orderItem = new OrderItem(null, cartItem.getName(), cartItem.getCount(), cartItem.getPrice(), cartItem.getTotalPrice(), orderId);
            //将订单项保存到数据库
            orderItemDao.saveOrderItem(orderItem);

            //更新库存和销量
            Book book = bookDao.queryBookById(cartItem.getId());
            book.setSales(book.getSales()+cartItem.getCount());
            book.setStock(book.getStock()-cartItem.getCount());
            bookDao.updateBook(book);
        }
        //清空购物车
        cart.clear();

        return orderId;
    }

    /**
     * 查询全部订单
     * @return
     */
    @Override
    public List<Order> showAllOrders() {
        List<Order> orderList = orderDao.queryOrders();
        return orderList;
    }

    /**
     * 发货
     * @param orderId
     * @return
     */
    @Override
    public int sendOrder(String orderId) {
        Integer status = orderDao.changeOrderStatus(orderId, 1);
        return status;
    }


}
